package com.example.screenprojection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.net.Inet4Address;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

public class NetworkUtils {

@RequiresApi(Build.VERSION_CODES.M)
public static String getLocalIpAddress (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network = connectivityManager.getActiveNetwork();
        if (network == null) {
                return null;
        }
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
        if (capabilities == null) {
                return null;
        }

        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                // 使用 WifiManager 获取 Wi-Fi IP
                return getWifiIpAddress(context);
        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                // 使用 NetworkInterface 获取移动网络 IP
                return getCellularIpAddress();
        }
        return null;
}

private static String getWifiIpAddress (Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        return String.format("%d.%d.%d.%d", ipAddress & 0xFF, (ipAddress >> 8) & 0xFF, (ipAddress >> 16) & 0xFF, (ipAddress >> 24) & 0xFF);
}

private static String getCellularIpAddress () {
        try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                for (NetworkInterface networkInterface : Collections.list(interfaces)) {
                        Enumeration<java.net.InetAddress> addresses = networkInterface.getInetAddresses();
                        for (java.net.InetAddress inetAddress : Collections.list(addresses)) {
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                        return inetAddress.getHostAddress();
                                }
                        }
                }
        } catch (SocketException e) {
                e.printStackTrace();
        }
        return null;
}
}
